package com.frame.project.service.system.menu.imp;

import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.persistence.criteria.Predicate;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.stereotype.Service;

import com.frame.common.constant.UserConstants;
import com.frame.common.enumutil.RemoveEnum;
import com.frame.common.utils.StringUtils;
import com.frame.common.utils.TreeUtils;
import com.frame.common.utils.security.ShiroUtils;
import com.frame.framework.web.domain.Ztree;
import com.frame.framework.web.service.imp.AbstractBaseService;
import com.frame.project.domain.system.menu.Menu;
import com.frame.project.domain.system.role.Role;
import com.frame.project.domain.system.user.User;
import com.frame.project.repository.system.menu.MenuRepository;
import com.frame.project.repository.system.role.RoleMenuRepository;
import com.frame.project.service.system.menu.MenuService;

/**
 * 
 * @className ：MenuServiceImpl
 * @describe ：菜单
 */
@Service
public class MenuServiceImpl extends AbstractBaseService<Menu> implements MenuService {

	public static final String PREMISSION_STRING = "perms[\"{0}\"]";
	
	@Autowired
	private MenuRepository menuRepository;
	
	@Autowired
	private RoleMenuRepository roleMenuRepository;
	
	/**
     * 根据用户查询菜单
     * 
     * @param user 用户信息
     * @return 菜单列表
     */
    @Override
    public List<Menu> selectMenusByUser(User user)
    {
        List<Menu> menus = new LinkedList<Menu>();
        
        // 管理员显示所有菜单信息
        if (user.isAdmin())
        {
            List<Map<String, Object>> menuAll = menuRepository.selectMenuNormalAll();
            menus = mapChangeMenus(menuAll);
        }
        else
        {
        	List<Map<String, Object>> userMenu = menuRepository.selectMenusByUserId(user.getId());
        	menus = mapChangeMenus(userMenu);
        
        }
        return TreeUtils.getChildPerms(menus, 0);
    }
    
    /**
     * 查询菜单集合
     * 
     * @return 所有菜单信息
     */
	@Override
    public List<Menu> selectMenuList(Menu menu)
    {
        List<Menu> menuList = null;
        User user = ShiroUtils.getSysUser();
        if (user.isAdmin())
        {
            menuList = selectMenuListBySearch(menu);
        }
        else
        {
            menu.getParams().put("userId", user.getId());
            List<Map<String, Object>> menuMap = menuRepository.selectMenuListByUserId(menu.getId(),menu.getMenuName(),menu.getVisible());
            menuList = mapChangeMenus(menuMap);
        }
        return menuList;
    }
    
    /**
     * 查询菜单集合
     * 
     * @return 所有菜单信息
     */
	@Override
    public List<Menu> selectMenuAll()
    {
        List<Menu> menuList = null;
        User user = ShiroUtils.getSysUser();
        if (user.isAdmin())
        {
            menuList = selectMenuListBySearch(new Menu());
        }
        else
        {
        	List<Map<String, Object>> menuMap = menuRepository.selectMenuAllByUserId(user.getId());
        	menuList = mapChangeMenus(menuMap);
        }
        return menuList;
    }
    
    /**
     * 根据用户ID查询权限
     * 
     * @param userId 用户ID
     * @return 权限列表
     */
    @Override
    public Set<String> selectPermsByUserId(Long userId)
    {
        List<String> perms = menuRepository.selectPermsByUserId(userId);
        Set<String> permsSet = new HashSet<>();
        for (String perm : perms)
        {
            if (StringUtils.isNotEmpty(perm))
            {
                permsSet.addAll(Arrays.asList(perm.trim().split(",")));
            }
        }
        return permsSet;
    }
    
    /**
     * 条件查询
     * @param menu
     * @return
     */
    public List<Menu> selectMenuListBySearch(Menu menu)
    {
    	List<Sort.Order> orders = new ArrayList<>();
		orders.add(new Sort.Order(Sort.Direction.ASC, "parentId"));
		orders.add(new Sort.Order(Sort.Direction.ASC, "orderNum"));
		Sort sort = Sort.by(orders);
		
    	List<Menu> dList = menuRepository.findAll((root, query, cb) ->{
			List<Predicate> list = new ArrayList<>();
			list.add(cb.and(cb.equal(root.get("removeStatus").as(Integer.class), RemoveEnum.NOT_REMOVE.getCode())));
			
			if(StringUtils.isNotBlank(menu.getMenuName())) {
				list.add(cb.and(cb.like(root.get("menuName").get("id").as(String.class), menu.getMenuName())));
			}
			
			if(StringUtils.isNotBlank(menu.getVisible())) {
				list.add(cb.and(cb.equal(root.get("visible").as(String.class), menu.getVisible())));
			}
			
			Predicate[] p = new Predicate[list.size()];
			return cb.and(list.toArray(p));
		},sort);
    	
    	return dList;
    }
    
    /**
     * 根据角色ID查询菜单
     * 
     * @param role 角色对象
     * @return 菜单列表
     */
    @Override
    public List<Ztree> roleMenuTreeData(Role role)
    {
        Long roleId = role.getId();
        List<Ztree> ztrees = new ArrayList<Ztree>();
        List<Menu> menuList = selectMenuAll();
        if (StringUtils.isNotNull(roleId))
        {
            List<String> roleMenuList = menuRepository.selectMenuTree(roleId);
            ztrees = initZtree(menuList, roleMenuList, true);
        }
        else
        {
            ztrees = initZtree(menuList, null, true);
        }
        return ztrees;
    }
    
    /**
     * 查询所有菜单
     * 
     * @return 菜单列表
     */
    @Override
    public List<Ztree> menuTreeData()
    {
        List<Menu> menuList = selectMenuListBySearch(new Menu());
        List<Ztree> ztrees = initZtree(menuList);
        return ztrees;
    }
    
    /**
     * 查询系统所有权限
     * 
     * @return 权限列表
     */
    @Override
    public LinkedHashMap<String, String> selectPermsAll()
    {
        LinkedHashMap<String, String> section = new LinkedHashMap<>();
        List<Menu> permissions = selectMenuAll();
        if (StringUtils.isNotEmpty(permissions))
        {
            for (Menu menu : permissions)
            {
                section.put(menu.getUrl(), MessageFormat.format(PREMISSION_STRING, menu.getPerms()));
            }
        }
        return section;
    }
    
    /**
     * 对象转菜单树
     * 
     * @param menuList 菜单列表
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Menu> menuList)
    {
        return initZtree(menuList, null, false);
    }
    
    /**
     * 对象转菜单树
     * 
     * @param menuList 菜单列表
     * @param roleMenuList 角色已存在菜单列表
     * @param permsFlag 是否需要显示权限标识
     * @return 树结构列表
     */
    public List<Ztree> initZtree(List<Menu> menuList, List<String> roleMenuList, boolean permsFlag)
    {
        List<Ztree> ztrees = new ArrayList<Ztree>();
        boolean isCheck = StringUtils.isNotNull(roleMenuList);
        for (Menu menu : menuList)
        {
            Ztree ztree = new Ztree();
            ztree.setId(menu.getId());
            ztree.setpId(menu.getParentId());
            ztree.setName(transMenuName(menu, permsFlag));
            ztree.setTitle(menu.getMenuName());
            if (isCheck)
            {
                ztree.setChecked(roleMenuList.contains(menu.getId() + menu.getPerms()));
            }
            ztrees.add(ztree);
        }
        return ztrees;
    }
    
    public String transMenuName(Menu menu, boolean permsFlag)
    {
        StringBuffer sb = new StringBuffer();
        sb.append(menu.getMenuName());
        if (permsFlag)
        {
            sb.append("<font color=\"#888\">&nbsp;&nbsp;&nbsp;" + menu.getPerms() + "</font>");
        }
        return sb.toString();
    }
    
    /**
     * 删除菜单管理信息
     * 
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public void deleteMenuById(Long menuId)
    {
        delete(menuId);
    }
    
    /**
     * 查询子菜单数量
     * 
     * @param parentId 菜单ID
     * @return 结果
     */
    @Override
    public Integer selectCountMenuByParentId(Long parentId)
    {
        return menuRepository.selectCountMenuByParentId(parentId);
    }
    
    /**
     * 查询菜单使用数量
     * 
     * @param menuId 菜单ID
     * @return 结果
     */
    @Override
    public Integer selectCountRoleMenuByMenuId(Long menuId)
    {
        return roleMenuRepository.selectCountRoleMenuByMenuId(menuId);
    }
    
    /**
     * 新增保存菜单信息
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public void insertMenu(Menu menu)
    {
    	if(StringUtils.isEmpty(menu.getUrl())) {
    		menu.setUrl("#");
    	}
        add(menu);
    }
    
    /**
     * 修改保存菜单信息
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public void updateMenu(Menu menu)
    {
    	Menu m = findById(menu.getId());
        m.setMenuName(menu.getMenuName());
        m.setParentId(menu.getParentId());
        m.setUrl(menu.getUrl());
        m.setTarget(menu.getTarget());
        m.setMenuType(menu.getMenuType());
        m.setVisible(menu.getVisible());
        m.setPerms(menu.getPerms());
        m.setIcon(menu.getIcon());
        m.setOrderNum(menu.getOrderNum());
        modify(m);
    }
    
    /**
     * 校验菜单名称是否唯一
     * 
     * @param menu 菜单信息
     * @return 结果
     */
    @Override
    public String checkMenuNameUnique(Menu menu)
    {
        Long menuId = StringUtils.isNull(menu.getId()) ? -1L : menu.getId();
        Menu info = menuRepository.findByMenuNameAndParentId(menu.getMenuName(), menu.getParentId());
        
        if (StringUtils.isNotNull(info) && info.getId() != menuId)
        {
            return UserConstants.POST_CODE_NOT_UNIQUE;
        }
        return UserConstants.POST_CODE_UNIQUE;
    }
    
    
    public List<Menu> mapChangeMenus(List<Map<String, Object>> menuMap){
    	
        List<Menu> menuList  = new LinkedList<Menu>();
        
    	for(int i = 0; i < menuMap.size(); i++) {
        	Map<String, Object> map = menuMap.get(i);
        	Menu m = new Menu();
        	m.setId(Long.valueOf(String.valueOf(map.get("id"))));
        	m.setParentId(Long.valueOf(String.valueOf(map.get("parentId"))));
        	m.setMenuName(String.valueOf(map.get("menuName")));
        	m.setUrl(String.valueOf(map.get("url")));
        	m.setVisible(String.valueOf(map.get("visible")));
        	m.setIsRefresh(String.valueOf(map.get("isRefresh")));
        	m.setPerms(String.valueOf(map.get("perms")));
        	m.setTarget(String.valueOf(map.get("target")));
        	m.setMenuType(String.valueOf(map.get("menuType")));
        	m.setIcon(String.valueOf(map.get("icon")));
        	m.setOrderNum(Integer.valueOf(String.valueOf(map.get("orderNum"))));
        	menuList.add(m);
        }
    	
    	return menuList;
    }
}
